package com.wontube.smr.dao.bo;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.ibatis.session.SqlSession;

import com.wontube.client.extension.utils.DateUtils;
import com.wontube.core.dao.mybatis.QueryExample;
import com.wontube.smr.client.model.po.Movie;
import com.wontube.smr.client.model.po.MovieGenre;
import com.wontube.smr.client.model.po.MovieWeek;
import com.wontube.smr.dao.mapper.MovieGenreMapper;
import com.wontube.smr.dao.mapper.MovieMapper;
import com.wontube.smr.dao.mapper.MovieWeekMapper;
import com.wontube.smr.pub.DefaultDBHelper;

/**
 * MovieDao 帮助类
 * 
 * @author hewc@wondershare.cn
 * 
 */
public class MovieDao {	
	private MovieDao() {
	}

	/**
	 * 批量插入数据库
	 * 
	 * @param movies
	 */
	public static void saveOrUpdate(List<Movie> movies, String genre) {
		// 批量session
		SqlSession session = DefaultDBHelper.getBatchSqlSession();
		try {
			int count = 0;
			// 时间戳
			Date now = Calendar.getInstance().getTime();
			MovieMapper mapper = session.getMapper(MovieMapper.class);
			for (Movie movie : movies) {
				count++;
				// itemUrl决定唯一性
				String itemUrl = movie.getItemUrl();
				QueryExample ex = new QueryExample();
				ex.or().addCriterion("item_url=", itemUrl);
				List<Movie> list = mapper.selectByExample(ex);
				if (list.size() > 0) {
					// update
					Movie po = list.get(0);
					po.setSortIndex(count);
					// 更新时间戳
					po.setVersion(now);
					mapper.updateByPrimaryKey(po);
				} else {
					// insert
					// movie.setId(UUID.randomUUID().toString());
					movie.setVersion(now);
					movie.setSortIndex(count);
					mapper.insert(movie);
				}
			}
			session.commit();
		} finally {
			session.close();
		}
	}

	/**
	 * 分批插入数据库（有序）
	 * 
	 * @param movies
	 *            视频列表
	 * @param genre
	 *            流派
	 * @param sortIndex
	 *            排序索引
	 */
	public static void saveOrUpdate(List<Movie> movies, int sortIndex) {
		// 批量session
		SqlSession session = DefaultDBHelper.getBatchSqlSession();
		try {
			int count = sortIndex;
			// 时间戳
			Date now = DateUtils.getNow();
			MovieMapper mapper = session.getMapper(MovieMapper.class);
			for (Movie movie : movies) {
				movie.setSortIndex(++count);
				movie.setVersion(now);
				
				// 更新排序				
				Movie tmp = mapper.selectByPrimaryKey(movie.getId());
				if (tmp != null) {					
					mapper.updateByPrimaryKey(movie);
				} else {
					// insert					
					mapper.insert(movie);
				}
			}
			session.commit();
		} finally {
			session.close();
		}
	}
	
	
	/**
	 * 更新抓取到的movie数据, 并更新相应的genre关联
	 * @param movies
	 * @param count
	 */
	public static void saveOrUpdateMoviesAndGenres(List<Movie> movies, int count){
		int index = count + 1;
		SqlSession session = DefaultDBHelper.getBatchSqlSession();
		Date now = DateUtils.getNow();
		try {
			MovieMapper mapper = session.getMapper(MovieMapper.class);
			MovieGenreMapper genreMapper = session.getMapper(MovieGenreMapper.class);
			for (Movie movie : movies) {			
				movie.setSortIndex(index++);
				movie.setVersion(now);
				String movieId = movie.getId();					
				Movie tmpMovie = mapper.selectByPrimaryKey(movieId);				
				if(tmpMovie != null){
					mapper.updateByPrimaryKey(movie);
				}else{					
					mapper.insert(movie);
				}
				
				//movie genre 关联	
				String genreNames = movie.getGenre();
				if(genreNames != null){		
					String[] genres = genreNames.split(",");
					for (String genre : genres) {
						QueryExample ex = new QueryExample();
						ex.or().addCriterion("movie_genre.movie_id=", movieId)
								.addCriterion("movie_genre.genre_name=", genre);
						
						if(genreMapper.countByExample(ex) < 1){
							//增加关联
							MovieGenre movieGenre = new MovieGenre();
							movieGenre.setId(UUID.randomUUID().toString());
							movieGenre.setMovieId(movieId);
							movieGenre.setGenreName(genre);
							genreMapper.insert(movieGenre);
						}
					}		
				}					
			}
			session.commit();
		} finally {
			session.close();
		}				
	}
	
	public static int savePopWeekMovie(List<String> list) {
		int count = 0;
		SqlSession session = DefaultDBHelper.getBatchSqlSession();
		try {
			MovieMapper movieMapper = session.getMapper(MovieMapper.class);
			MovieWeekMapper movieWeekMapper = session.getMapper(MovieWeekMapper.class);
			List<Movie> movies = new ArrayList<Movie>();
			for (String title : list) {
				QueryExample ex = new QueryExample();
				ex.or().addCriterion("movie.title = ", title);
				movies = movieMapper.selectByExample(ex);
				if (movies.size() > 0) {
					Movie po = movies.get(0);
					String movieId = po.getId();
					QueryExample movieWeekEx = new QueryExample();
					movieWeekEx.or().addCriterion("movie_id=", movieId);
					List<MovieWeek> movieWeekList = movieWeekMapper.selectByExample(movieWeekEx);
					if (movieWeekList.size() > 0) {
						MovieWeek movieWeek = movieWeekList.get(0);
						movieWeek.setSortIndex(++count);
						movieWeek.setVersion(DateUtils.getNow());
						movieWeekMapper.updateByPrimaryKey(movieWeek);
					} else {
						MovieWeek movieWeek = new MovieWeek();
						movieWeek.setId(UUID.randomUUID().toString());
						movieWeek.setMovieId(po.getId());
						movieWeek.setSortIndex(++count);
						movieWeek.setVersion(DateUtils.getNow());
						movieWeekMapper.insert(movieWeek);
					}
				}
			}
			session.commit();
		} finally {
			session.close();
		}
		return count;
	}
}
